/*
This software is distributed under the Simplified BSD License:

Copyright (c) 2008, Chris Venter <chris.venter@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
    	this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
    	this list of conditions and the following disclaimer in the documentation 
    	and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
DAMAGE.
*/
#ifndef GENERIK_POSTGRES_DBSPI_H
#define GENERIK_POSTGRES_DBSPI_H

/** \file postgres.h
This file implements functionality for use in postgres SPI code.
*/

#include "../database/postgres.h"

/* The following has to be extern C'd, otherwise postgres does will not recognise
a shared object built with this included.
*/
extern "C"
{
	#include <postgres.h>
	#include <fmgr.h>
	#include <executor/spi.h>
	#include <funcapi.h>

	#ifdef PG_MODULE_MAGIC
		PG_MODULE_MAGIC;
	#endif
}

#include <iostream>
#include <sstream>
#include <string>
#include <list>

#ifdef POSTGRES_DBSPI

#define POSTGRES_DEFINE_FUNC(FUNC) \
	extern "C" { \
	PG_FUNCTION_INFO_V1(FUNC); \
	Datum FUNC(PG_FUNCTION_ARGS)

#define POSTGRES_END_FUNC }

#define POSTGRES_GET_DBSPI \
	generik::postgres_dbspi _postgres_dbspi_; \
	generik::dbspi& _dbspi_handle_ = _postgres_dbspi_
	
#define DBSPI_DEFINE_FUNC(FUNC) POSTGRES_DEFINE_FUNC(FUNC)
#define DBSPI_END_FUNC POSTGRES_END_FUNC
#define DBSPI_GET_HANDLE POSTGRES_GET_DBSPI
#define DBSPI_HANDLE &_dbspi_handle_
#define DBSPI_GETARG_INT(INDEX) PG_GETARG_INT32(INDEX)
#define DBSPI_RETURN_INT(VALUE) PG_RETURN_INT32(VALUE)

#define DBSPI_MESSAGE_OUTPUT(WHAT, SOURCE, MESSAGE) \
	{ \
		std::stringstream cc; cc<<"["<<(SOURCE)<<"] "<<MESSAGE<<std::flush; \
		elog(WHAT, "%s", cc.str().c_str()); \
	}

#define DBSPI_LOG_MESSAGE_FROM_SOURCE(SOURCE, MESSAGE) DBSPI_MESSAGE_OUTPUT(INFO, SOURCE, MESSAGE)
#define DBSPI_LOG(MESSAGE) DBSPI_LOG_MESSAGE_FROM_SOURCE(__FUNCTION__, MESSAGE)

#define DBSPI_ERROR_MESSAGE_FROM_SOURCE(SOURCE, MESSAGE) DBSPI_MESSAGE_OUTPUT(ERROR, SOURCE, MESSAGE)
#define DBSPI_ERROR(MESSAGE) DBSPI_ERROR_MESSAGE_FROM_SOURCE(__FUNCTION__, MESSAGE)

#define DBSPI_TRACER DBSPI_LOG("[running]")

#endif // POSTGRES_DBSPI

std::string get_module_name();

#define CHARARRAY (const char*[])
#define VOIDARG CHARARRAY{0}
/** Creates an SQL command to register a function.
This function takes arguments specifying the decleration of a SPI function, and spits out
an SQL command which will register the SPI function and make it available to the client 
when executed.
*/
std::string make_register_sql(const char* rettype, const char* funcname, const char** argtypes)
{
	std::string result = "CREATE OR REPLACE FUNCTION ";
	result += funcname;
	result += "(";
	int i = 0;
	while (argtypes[i] != 0)
	{
		result += argtypes[i];
		i++;
		if (argtypes[i] != 0) result += ", ";
	}
	result += ") RETURNS ";
	result += rettype;
	result += " AS '";
	result += get_module_name() + ".soo";
	result += "', 'dbspi_";
	result += funcname;
	result += "' LANGUAGE C STRICT";
	return result;
}

std::list<std::string>* get_register_functions();

/** This function returns a set of SQL commands required to register the functions in this module.
It should automatically be set up by generik::postgres::load_module() to be callable from the client.
*/
//export
DBSPI_DEFINE_FUNC(dbspi_get_register_functions)
{
	if (SRF_IS_FIRSTCALL())
	{
		FuncCallContext* funcctx = SRF_FIRSTCALL_INIT();
		MemoryContext oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
		
		// get the entries and add them to the funcctx
		std::list<std::string>* entries = get_register_functions();
		funcctx->user_fctx = entries;
		
		MemoryContextSwitchTo(oldcontext);
	}
	
	// get the entries from the funcctx
	FuncCallContext* funcctx = SRF_PERCALL_SETUP();
	std::list<std::string>* entries = (std::list<std::string>*)(funcctx->user_fctx);
	
	std::list<std::string>::iterator i = entries->begin();
	if (i != entries->end())
	{
		int size = i->size();
		
		text* output = (text *)palloc(VARHDRSZ + size);
		SET_VARSIZE(output, VARHDRSZ + size);
		memcpy(VARDATA(output), i->c_str(), size);

		DBSPI_LOG(VARDATA(output));
		
		Datum result = (Datum(output));
		
		// remove i from the entries
		entries->erase(i);
		SRF_RETURN_NEXT(funcctx, result);
	}
	// this means there are no more entries left:
	delete entries;
	
	SRF_RETURN_DONE(funcctx);
}
POSTGRES_END_FUNC

namespace generik
{

	/** Implements SPI functionality for the PostgreSQL database backend.
	This class enables a backend function to make queries of its own, using SPI calls.
	*/
	struct postgres_dbspi
	: dbspi
	{
		postgres_dbspi()
		{
			GENERIK_TRACER;
			SPI_connect();
		}
		
		~postgres_dbspi()
		{
			GENERIK_TRACER;
			SPI_finish();
		}
		
		inline void runquery(const std::string& cmd, callback cb, void* object)
		{
			if (SPI_exec(cmd.c_str(), 0) > 0)
			{
				if (SPI_tuptable != NULL)
				{
					TupleDesc tupdesc = SPI_tuptable->tupdesc;
					int nfields = tupdesc->natts;
					SPITupleTable *tuptable = SPI_tuptable;
					
					int rows = SPI_processed;
					for (int i = 0; i < rows; i++)
					{
						// for each row, get all the fields and run the callback with the object
						char* values[nfields];
						for (int j = 0; j < nfields; j++)
						{
							HeapTuple tuple = tuptable->vals[i];
							values[j] = SPI_getvalue(tuple, tupdesc, j+1);
						}
						(*cb)(nfields, values, object);
					}
				}
			}
		}
	};
	
}

#endif










